/*
 * Powered By 
 * Since 2010 - 2016
 */

package com.rf.business.control;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.rf.sys.frm.BaseController;
import com.rf.sys.model.DepUser;
import com.rf.sys.model.Department;
import com.rf.sys.model.User;
import com.rf.sys.service.DepartmentService;
import com.rf.sys.utils.ConfigUtils;
import com.rf.sys.utils.JsonUtils;
import com.rf.sys.utils.PageUtils;
import com.rf.sys.utils.UuidUtil;
import com.rf.business.bean.NoticBean;
import com.rf.business.model.Notice;
import com.rf.business.model.NoticeDep;
import com.rf.business.service.NoticeDepService;
import com.rf.business.service.NoticeService;

@Controller
@RequestMapping("/bus/notice")
public class NoticeController extends BaseController{
	/**
	 * 日志
	 */
	private static Logger log = LoggerFactory.getLogger(NoticeController.class);
	private static final long serialVersionUID = -120161117110154993L;
	
	@Resource
	private NoticeService noticeService;
	@Resource
	private DepartmentService departmentService;
	@Resource
	private NoticeDepService noticeDepService;
	/**
	 * 初始化页面信息
	 * @param request,response
	 * @return ModelAndView
	 * @throws ServletException,IOException
	 */
	@RequestMapping(value = "index")
    public ModelAndView index (HttpServletRequest request, HttpServletResponse response) throws Exception{
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("/business/notice/notice_list");
		return modelAndView; 
    }
    
    /**
	 * 搜索页面信息
	 * @param Page,request,response
	 * @return JSON
	 * @throws ServletException,IOException
	 */
    @RequestMapping(value = "query")
    @ResponseBody
    public void query (PageUtils pageUtils, Notice notice, HttpServletRequest request, HttpServletResponse response ) throws Exception{
    	//获取分页、查询参数，进行数据封装
    	
    	Map searchMap = noticeService.getNoticePage(notice, pageUtils);
    	super.responsePrint(request, response, JsonUtils.mapToJson(searchMap));
    }
    
    /**
     * 编辑页面初始化
     * @param request,response
	 * @return ModelAndView
	 * @throws ServletException,IOException
     */
    @RequestMapping(value = "edit")
    public ModelAndView edit (HttpServletRequest request, HttpServletResponse response ) throws Exception{
    	ModelAndView modelAndView = new ModelAndView();
    	Session session = SecurityUtils.getSubject().getSession();
		String id = request.getParameter("id");
		Notice notice = new Notice();
		NoticBean nB = new NoticBean();
		if(id != null && !id.equals("")){
			User user = (User)session.getAttribute("userSession");
			DepUser depUser=new DepUser();
			depUser.setUserId(user.getId());
			StringBuffer depName = new StringBuffer();
			StringBuffer depId1 = new StringBuffer();
			NoticeDep nd = new NoticeDep();
			nd.setnId(id);
			notice = noticeService.getNoticeByID(id);
			List<NoticeDep> list =  noticeDepService.getNoticeDep(nd);
			if(list != null && list.size() > 0){
				for(NoticeDep nD : list){
				Department dep = departmentService.getDepartmentByID(nD.getDepId());
				depName.append(dep.getName()).append(",");
				depId1.append(dep.getId()).append(",");
				}
			}
		
			nB.setId(notice.getId());
			nB.setTitel(notice.getTitel());
			nB.setContent(notice.getContent());
			nB.setCreateTime(notice.getCreateTime());
			nB.setUserName(user.getUserName());
			nB.setDepName(depName.substring(0, depName.length()-1));
			nB.setDepId(depId1.substring(0, depId1.length()-1));
		}else{
//			notice.setState(ConfigUtils.ENABLESTATE);
		}
		modelAndView.addObject("notice", nB);
        modelAndView.setViewName("/business/notice/notice_edit");
        return modelAndView; 
    }
    
    /**
     * 保存数据信息
     * @param Notice,request,response
	 * @return ModelAndView
	 * @throws ServletException,IOException
     */
    @RequestMapping(value = "save")
    public void save (NoticBean noticBean, HttpServletRequest request, HttpServletResponse response ) throws Exception{
    	Session session = SecurityUtils.getSubject().getSession();
    	String ret = "success";
		if(noticBean !=null){
			Notice notice = new Notice();
			notice.setTitel(noticBean.getTitel());
			notice.setContent(noticBean.getContent());
			if(noticBean.getId()!=null && !noticBean.getId().equals("")){
				//修改
				notice.setId(noticBean.getId());
				noticeService.updateNotice(notice);
				/**
				 *获取关联表中数据，先删除，后新增 
				 */
				NoticeDep nd = new NoticeDep();
				nd.setnId(noticBean.getId());
				List<NoticeDep> list =  noticeDepService.getNoticeDep(nd);
				if(list != null && list.size() > 0){
					for(NoticeDep nd1 : list){
						noticeDepService.deleteNoticeDep(nd1.getId());
					}
				}
				if(noticBean.getDepId() != null &&  !noticBean.getDepId().equals("")){
					String [] depIdsArr = noticBean.getDepId().split(",");
					for(int i=0;i<depIdsArr.length;i++){
						NoticeDep n = new NoticeDep();
						n.setId(UuidUtil.get32UUID());
						n.setDepId(depIdsArr[i]);
						n.setnId(notice.getId());
						noticeDepService.addNoticeDep(n);
					}
				}
			}else{
				//新增
				notice.setId(UuidUtil.get32UUID());
				notice.setCreateTime(new Date());
				notice.setCreateUser((String)session.getAttribute("userSessionId"));
				noticeService.addNotice(notice);
				if(noticBean.getDepId() != null &&  !noticBean.getDepId().equals("")){
					String [] depIdsArr = noticBean.getDepId().split(",");
					for(int i=0;i<depIdsArr.length;i++){
						NoticeDep n = new NoticeDep();
						n.setId(UuidUtil.get32UUID());
						n.setDepId(depIdsArr[i]);
						n.setnId(notice.getId());
						n.setIsRead("0");
						noticeDepService.addNoticeDep(n);
					}
				}
			}
		}
		super.resPrint(request, response, ret);//成功 
    }
    
    /**
     * 删除数据信息
     * @param request,response
	 * @return JSON
	 * @throws ServletException,IOException
	 */
    @RequestMapping(value = "delete")
    @ResponseBody
    public void delete (HttpServletRequest request, HttpServletResponse response) throws Exception{
    	JSONObject returnObj = new JSONObject();
    	String ids = request.getParameter("ids");
    	String [] idsArr = ids.split(",");
    	for(int i=0;i<idsArr.length;i++){
    		noticeService.deleteNotice(idsArr[i]);
    	}
		returnObj.element("message", "success");//成功
		super.responseJson(request, response, returnObj.toString());
    }
    
    /**
     * 更新数据状态
     * @param notice,request,response
	 * @return JSON
	 * @throws ServletException,IOException
	 */
    @RequestMapping(value = "updateState")
    @ResponseBody
    public void updateState (Notice notice, HttpServletRequest request, HttpServletResponse response) throws Exception{
    	JSONObject returnObj = new JSONObject();
    	noticeService.updateNotice(notice);
		returnObj.element("message", "success");//成功
		super.responseJson(request, response, returnObj.toString());
    }
}


